import React, { Suspense } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { Spin } from 'antd';
import { routeConfigs, RouteConfig } from '@/config/routes';

// 加载中组件
const RouteLoading: React.FC = () => (
  <div className="flex items-center justify-center min-h-[200px]">
    <Spin size="large" tip="页面加载中..." />
  </div>
);

// 路由守卫高阶组件
interface RouteGuardProps {
  config: RouteConfig;
  children: React.ReactNode;
}

const RouteGuard: React.FC<RouteGuardProps> = ({ config, children }) => {
  // 这里可以添加权限检查逻辑
  const { meta } = config;
  
  // 如果需要权限验证
  if (meta?.permission) {
    // 这里可以检查用户权限
    // const hasPermission = checkUserPermission(meta.permission);
    // if (!hasPermission) {
    //   return <Navigate to="/403" replace />;
    // }
  }
  
  return <>{children}</>;
};

// 生成单个路由组件
const generateRouteElement = (config: RouteConfig): React.ReactElement => {
  const { component: Component, redirect, meta } = config;
  
  // 如果是重定向路由
  if (redirect) {
    return <Navigate to={redirect} replace />;
  }
  
  // 正常组件路由
  return (
    <RouteGuard config={config}>
      <Suspense fallback={<RouteLoading />}>
        <Component />
      </Suspense>
    </RouteGuard>
  );
};

// 路由管理器类
export class RouteManager {
  private static instance: RouteManager;
  private configs: RouteConfig[];
  
  private constructor() {
    this.configs = routeConfigs;
  }
  
  // 单例模式
  public static getInstance(): RouteManager {
    if (!RouteManager.instance) {
      RouteManager.instance = new RouteManager();
    }
    return RouteManager.instance;
  }
  
  // 获取所有路由配置
  public getRouteConfigs(): RouteConfig[] {
    return this.configs;
  }
  
  // 添加路由配置
  public addRouteConfig(config: RouteConfig): void {
    this.configs.push(config);
  }
  
  // 移除路由配置
  public removeRouteConfig(path: string): void {
    this.configs = this.configs.filter(config => config.path !== path);
  }
  
  // 根据路径获取配置
  public getRouteConfig(path: string): RouteConfig | undefined {
    return this.configs.find(config => config.path === path);
  }
  
  // 生成所有路由组件
  public generateRoutes(): React.ReactElement {
    return (
      <Routes>
        {this.configs.map((config, index) => (
          <Route
            key={config.path || index}
            path={config.path}
            element={generateRouteElement(config)}
          />
        ))}
      </Routes>
    );
  }
  
  // 根据条件过滤路由
  public filterRoutes(predicate: (config: RouteConfig) => boolean): RouteConfig[] {
    return this.configs.filter(predicate);
  }
  
  // 获取需要认证的路由
  public getAuthRoutes(): RouteConfig[] {
    return this.filterRoutes(config => config.meta?.requireAuth === true);
  }
  
  // 获取公开路由
  public getPublicRoutes(): RouteConfig[] {
    return this.filterRoutes(config => config.meta?.requireAuth !== true);
  }
  
  // 根据权限过滤路由
  public getRoutesByPermission(permissions: string[]): RouteConfig[] {
    return this.filterRoutes(config => {
      if (!config.meta?.permission) return true;
      return permissions.includes(config.meta.permission);
    });
  }
}

// 导出单例实例
export const routeManager = RouteManager.getInstance();

// 生成路由的Hook
export const useRouteManager = () => {
  return {
    generateRoutes: () => routeManager.generateRoutes(),
    getRouteConfigs: () => routeManager.getRouteConfigs(),
    getRouteConfig: (path: string) => routeManager.getRouteConfig(path),
    addRouteConfig: (config: RouteConfig) => routeManager.addRouteConfig(config),
    removeRouteConfig: (path: string) => routeManager.removeRouteConfig(path),
    getAuthRoutes: () => routeManager.getAuthRoutes(),
    getPublicRoutes: () => routeManager.getPublicRoutes(),
    getRoutesByPermission: (permissions: string[]) => routeManager.getRoutesByPermission(permissions),
  };
};

// 生成受保护的路由组件
export const ProtectedRoutes: React.FC = () => {
  return routeManager.generateRoutes();
};

// 导出路由配置用于菜单生成
export const getMenuRoutes = (): RouteConfig[] => {
  return routeManager.getRouteConfigs().filter(config => 
    config.path !== '/' && 
    config.path !== '*' && 
    config.meta?.title
  );
}; 